<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\ScenicSpot;

class ScenicSpotService
{
    public static function list($page = 1, $length = 10, $name = '', $order = ['views', 'desc'])
    {
        $offset = ($page - 1) * $length;
        $query = ScenicSpot::select(['id', 'name', 'longitude', 'latitude', 'desc', 'thumb', 'views', 'tags'])->where('area_id', 1);

        if (!empty($name)) {
            $query->where('name', 'like', "%{$name}%");
        }

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderBy($order[0], $order[1])->get()->toArray();

        foreach ($list as $key=>$item) {
            $list[$key]['thumb'] = full_url($item['thumb']);
            $list[$key]['tags'] = explode("\n", $item['tags']);
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function detail($id, $lng = 0, $lat = 0)
    {
        $detail = ScenicSpot::select(['id', 'name', 'longitude', 'latitude', 'desc', 'thumb', 'images', 'video', 'views', 'audio', 'share_bg', 'tags', 'created_time', 'address'])->where('id', $id)->first();

        if (!$detail) {
            throw new \Exception('不存在的景点');
        }

        $detail = $detail->toArray();

        $detail['images'] = explode(',', $detail['images']);

        array_walk($detail['images'], function(&$item) {
            $item = full_url($item);
        });

        if ($detail['video']) {
            array_unshift($detail['images'], full_url($detail['video']));
        }

        $detail['thumb'] = full_url($detail['thumb']);
        $detail['share_bg'] = full_url($detail['share_bg']);
        $detail['video'] = full_url($detail['video']);
        $detail['audio'] = full_url($detail['audio']);
        $detail['tags'] = explode("\n", $detail['tags']);
        $detail['distance'] = get_two_point_distance($lng, $lat, $detail['longitude'], $detail['latitude']);

        return $detail;
    }
}